<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>优惠券发放任务管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>优惠券发放任务管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#taskModal">
            新增发放任务
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-3">
                <input type="number" id="searchShopNumber" class="form-control" placeholder="输入店铺编号搜索">
            </div>
            <div class="col-md-3">
                <select id="searchTemplateId" class="form-select">
                    <option value="">全部模板</option>
                </select>
            </div>
            <div class="col-md-3">
                <select id="searchTaskStatus" class="form-select">
                    <option value="">全部状态</option>
                    <option value="0">待执行</option>
                    <option value="1">执行中</option>
                    <option value="2">执行失败</option>
                    <option value="3">执行成功</option>
                    <option value="4">已取消</option>
                </select>
            </div>
            <div class="col-md-3">
                <button class="btn btn-success w-100" onclick="queryTaskList(1)">搜索</button>
            </div>
        </div>
    </div>

    <!-- 发放任务列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>任务ID</th>
                    <th>店铺编号</th>
                    <th>优惠券模板</th>
                    <th>发放数量</th>
                    <th>任务状态</th>
                    <th>创建时间</th>
                    <th>执行时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="taskTableBody">
                <tr><td colspan="8" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑发放任务弹窗 -->
<div class="modal fade" id="taskModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增发放任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="taskForm">
                    <input type="hidden" id="taskId">
                    <div class="mb-3">
                        <label for="shopNumber" class="form-label">店铺编号 <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="shopNumber" required placeholder="平台任务填99999，店铺任务填对应店铺编号">
                    </div>
                    <div class="mb-3">
                        <label for="couponTemplateId" class="form-label">优惠券模板 <span class="text-danger">*</span></label>
                        <select class="form-select" id="couponTemplateId" required>
                            <option value="">请选择模板</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="sendNum" class="form-label">发放数量 <span class="text-danger">*</span></label>
                        <input type="number" min="1" class="form-control" id="sendNum" required placeholder="请输入发放数量">
                    </div>
                    <div class="mb-3">
                        <label for="targetUserType" class="form-label">发放对象 <span class="text-danger">*</span></label>
                        <select class="form-select" id="targetUserType" required>
                            <option value="0">指定用户</option>
                            <option value="1">全部用户</option>
                            <option value="2">新用户</option>
                            <option value="3">老用户</option>
                        </select>
                    </div>
                    <div class="mb-3" id="targetUserIdsGroup" style="display: none;">
                        <label for="targetUserIds" class="form-label">指定用户ID</label>
                        <input type="text" class="form-control" id="targetUserIds" placeholder="发放对象为指定用户时填写，多个ID用逗号分隔">
                    </div>
                    <div class="mb-3">
                        <label for="taskStatus" class="form-label">任务状态 <span class="text-danger">*</span></label>
                        <select class="form-select" id="taskStatus" required>
                            <option value="0">待执行</option>
                            <option value="1">执行中</option>
                            <option value="2">执行失败</option>
                            <option value="3">执行成功</option>
                            <option value="4">已取消</option>
                        </select>
                    </div>
                    <div class="mb-3" id="executeTimeGroup" style="display: none;">
                        <label for="executeTime" class="form-label">执行时间</label>
                        <input type="datetime-local" class="form-control" id="executeTime">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveTask()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;

    window.onload = function () {
        // 加载模板列表
        SelectData.loadCouponTemplates("couponTemplateId");
        SelectData.loadCouponTemplates("searchTemplateId");

        // 监听发放对象变化
        document.getElementById("targetUserType").addEventListener("change", function () {
            document.getElementById("targetUserIdsGroup").style.display = this.value === "0" ? "block" : "none";
        });

        // 监听任务状态变化
        document.getElementById("taskStatus").addEventListener("change", function () {
            const showExecuteTime = [1, 2, 3].includes(parseInt(this.value));
            document.getElementById("executeTimeGroup").style.display = showExecuteTime ? "block" : "none";
        });

        queryTaskList(currentPage);
    };

    // 格式化发放对象
    function formatTargetUserType(type, userIds) {
        const typeMap = {
            0: `指定用户（${userIds || "未指定"}）`,
            1: "全部用户",
            2: "新用户",
            3: "老用户"
        };
        return typeMap[type] || "未知对象";
    }

    // 查询发放任务列表
    async function queryTaskList(pageNum) {
        try {
            const shopNumber = document.getElementById("searchShopNumber").value;
            const templateId = document.getElementById("searchTemplateId").value;
            const status = document.getElementById("searchTaskStatus").value;

            const res = await axios.get("/api/coupon-tasks/page", {
                params: {
                    pageNum,
                    pageSize,
                    shopNumber: shopNumber || undefined,
                    couponTemplateId: templateId || undefined,
                    status: status || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("taskTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(task => {
                const row = `
                        <tr>
                            <td>${task.id}</td>
                            <td>${task.shopNumber}</td>
                            <td>${task.couponTemplate?.name || "未知模板"}</td>
                            <td>${task.sendNum}</td>
                            <td>${Common.formatTaskStatus(task.status)}</td>
                            <td>${Common.formatDate(task.createTime)}</td>
                            <td>${task.executeTime ? Common.formatDate(task.executeTime) : "无"}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editTask(${task.id})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteTask(${task.id})">删除</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryTaskList);
        } catch (err) {
            Common.errorMsg("查询发放任务失败：" + err.message);
            document.getElementById("taskTableBody").innerHTML = '<tr><td colspan="8" class="text-center">查询失败</td></tr>';
        }
    }

    // 编辑发放任务
    async function editTask(taskId) {
        try {
            const res = await axios.get(`/api/coupon-tasks/${taskId}`);
            const task = res.data;

            document.getElementById("taskId").value = task.id;
            document.getElementById("shopNumber").value = task.shopNumber;
            document.getElementById("couponTemplateId").value = task.couponTemplateId;
            document.getElementById("sendNum").value = task.sendNum;
            document.getElementById("targetUserType").value = task.targetUserType || 1;
            document.getElementById("targetUserIds").value = task.targetUserIds || "";
            document.getElementById("taskStatus").value = task.status;
            document.getElementById("executeTime").value = task.executeTime ? moment(task.executeTime).format("YYYY-MM-DDTHH:mm") : "";
            document.getElementById("modalTitle").textContent = "编辑发放任务";

            // 显示对应字段
            document.getElementById("targetUserIdsGroup").style.display = task.targetUserType === 0 ? "block" : "none";
            const showExecuteTime = [1, 2, 3].includes(task.status);
            document.getElementById("executeTimeGroup").style.display = showExecuteTime ? "block" : "none";

            new bootstrap.Modal(document.getElementById("taskModal")).show();
        } catch (err) {
            Common.errorMsg("加载发放任务信息失败：" + err.message);
        }
    }

    // 保存发放任务
    async function saveTask() {
        const shopNumber = document.getElementById("shopNumber").value;
        const couponTemplateId = document.getElementById("couponTemplateId").value;
        const sendNum = document.getElementById("sendNum").value;
        const targetUserType = document.getElementById("targetUserType").value;
        const taskStatus = document.getElementById("taskStatus").value;
        const executeTime = document.getElementById("executeTime").value;
        const taskId = document.getElementById("taskId").value;

        // 校验必填字段
        if (!shopNumber || !couponTemplateId || !sendNum || !targetUserType || !taskStatus) {
            Common.errorMsg("请填写必填字段！");
            return;
        }

        // 构建任务数据
        const taskData = {
            shopNumber: parseInt(shopNumber),
            couponTemplateId: parseInt(couponTemplateId),
            sendNum: parseInt(sendNum),
            targetUserType: parseInt(targetUserType),
            targetUserIds: document.getElementById("targetUserIds").value || "",
            status: parseInt(taskStatus),
            executeTime: executeTime ? new Date(executeTime).getTime() : null,
            createTime: taskId ? undefined : new Date().getTime() // 新增时自动生成创建时间
        };

        try {
            if (taskId) {
                taskData.id = parseInt(taskId);
                await axios.put("/api/coupon-tasks", taskData);
                Common.successMsg("编辑发放任务成功！");
            } else {
                await axios.post("/api/coupon-tasks", taskData);
                Common.successMsg("新增发放任务成功！");
            }

            bootstrap.Modal.getInstance(document.getElementById("taskModal")).hide();
            queryTaskList(currentPage);
            document.getElementById("taskForm").reset();
            document.getElementById("taskId").value = "";
            document.getElementById("modalTitle").textContent = "新增发放任务";
            document.getElementById("targetUserIdsGroup").style.display = "none";
            document.getElementById("executeTimeGroup").style.display = "none";
        } catch (err) {
            Common.errorMsg("保存发放任务失败：" + err.message);
        }
    }

    // 删除发放任务（逻辑删除）
    function deleteTask(taskId) {
        Common.confirmMsg("确定要删除该发放任务吗？（逻辑删除）", async () => {
            try {
                await axios.delete(`/api/coupon-tasks/${taskId}`);
                Common.successMsg("删除发放任务成功！");
                queryTaskList(currentPage);
            } catch (err) {
                Common.errorMsg("删除发放任务失败：" + err.message);
            }
        });
    }
</script>
</body>
</html>